// API基础URL
const API_BASE_URL = '/api';

// DOM元素（将在DOMContentLoaded中初始化）
let loginSection, mainContent, loginForm, logoutBtn;
let viewInboundModal, viewOutboundModal, inboundDetailContent, outboundDetailContent;
let addTransferModal, addTransferForm;
let closeModalBtns;

// 表格元素
let inboundTableBody, outboundTableBody, inventoryQueryTableBody, stocktakingTableBody, transferTableBody, outboundQueryTableBody;

// 按钮元素
let addInboundBtn, addOutboundBtn, addTransferBtn;
let searchInventoryBtn, startStocktakingBtn;
let queryOutboundSubmitBtn, queryOutboundResetBtn;
let sendInstructionsBtn; // 新增下发指令按钮

// 输入元素
let inventorySearch;
let queryMaterialName, queryMaterialCode, queryLocation, queryAisle, queryRow, queryColumn, queryLevel, queryEndEquipment, queryAisleNumber;

// JWT令牌
let authToken = localStorage.getItem('authToken');

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，开始初始化...');
    
    // 初始化DOM元素
    initializeDOMElements();
    
    // 检查用户是否已登录
    if (authToken) {
        showMainContent();
        loadAllData();
    } else {
        showLoginSection();
    }
    
    // 绑定事件监听器
    bindEventListeners();
});

// 初始化DOM元素
function initializeDOMElements() {
    // 认证相关元素
    loginSection = document.getElementById('loginSection');
    mainContent = document.getElementById('mainContent');
    loginForm = document.getElementById('loginForm');
    logoutBtn = document.getElementById('logoutBtn');

    // 模态框元素
    viewInboundModal = document.getElementById('viewInboundModal');
    viewOutboundModal = document.getElementById('viewOutboundModal');
    inboundDetailContent = document.getElementById('inboundDetailContent');
    outboundDetailContent = document.getElementById('outboundDetailContent');
    addTransferModal = document.getElementById('addTransferModal');
    addTransferForm = document.getElementById('addTransferForm');
    closeModalBtns = document.querySelectorAll('.close');

    // 表格元素
    inboundTableBody = document.querySelector('#inboundTable tbody');
    outboundTableBody = document.querySelector('#outboundTable tbody');
    inventoryQueryTableBody = document.querySelector('#inventoryQueryTable tbody');
    stocktakingTableBody = document.querySelector('#stocktakingTable tbody');
    transferTableBody = document.querySelector('#transferTable tbody');
    outboundQueryTableBody = document.querySelector('#outboundQueryTable tbody');

    // 按钮元素
    addInboundBtn = document.getElementById('addInboundBtn');
    addOutboundBtn = document.getElementById('addOutboundBtn');
    addTransferBtn = document.getElementById('addTransferBtn');
    searchInventoryBtn = document.getElementById('searchInventoryBtn');
    startStocktakingBtn = document.getElementById('startStocktakingBtn');
    queryOutboundSubmitBtn = document.getElementById('queryOutboundSubmitBtn');
    queryOutboundResetBtn = document.getElementById('queryOutboundResetBtn');
    sendInstructionsBtn = document.getElementById('sendInstructionsBtn'); // 新增下发指令按钮

    // 输入元素
    inventorySearch = document.getElementById('inventorySearch');
    queryMaterialName = document.getElementById('queryMaterialName');
    queryMaterialCode = document.getElementById('queryMaterialCode');
    queryLocation = document.getElementById('queryLocation');
    queryAisle = document.getElementById('queryAisle');
    queryRow = document.getElementById('queryRow');
    queryColumn = document.getElementById('queryColumn');
    queryLevel = document.getElementById('queryLevel');
    queryEndEquipment = document.getElementById('queryEndEquipment');
    queryAisleNumber = document.getElementById('queryAisleNumber');
}

// 绑定事件监听器
function bindEventListeners() {
    console.log('开始绑定事件监听器...');
    
    // 登录表单提交
    if (loginForm) {
        loginForm.addEventListener('submit', handleLogin);
        console.log('已绑定登录表单提交事件');
    }
    
    // 登出按钮
    if (logoutBtn) {
        logoutBtn.addEventListener('click', handleLogout);
        console.log('已绑定登出按钮点击事件');
    }
    
    // 关闭模态框按钮
    if (closeModalBtns) {
        closeModalBtns.forEach(btn => {
            btn.addEventListener('click', closeAllModals);
        });
        console.log('已绑定关闭模态框按钮点击事件');
    }
    
    // 点击模态框外部关闭
    window.addEventListener('click', function(event) {
        const modals = [viewInboundModal, viewOutboundModal, addTransferModal];
        if (modals.includes(event.target)) {
            closeAllModals();
        }
    });
    
    // 创建入库单据按钮
    if (addInboundBtn) {
        addInboundBtn.addEventListener('click', function() {
            window.location.href = 'create_inbound.html';
        });
    }
    
    // 创建出库单据按钮
    if (addOutboundBtn) {
        addOutboundBtn.addEventListener('click', function() {
            window.location.href = 'create_outbound.html';
        });
    }
    
    // 创建移库单按钮
    if (addTransferBtn) {
        addTransferBtn.addEventListener('click', openAddTransferModal);
    }
    
    // 库存搜索按钮
    if (searchInventoryBtn) {
        searchInventoryBtn.addEventListener('click', handleInventorySearch);
    }
    
    // 开始盘点按钮
    if (startStocktakingBtn) {
        startStocktakingBtn.addEventListener('click', handleStartStocktaking);
    }
    
    // 查询出库事件
    if (queryOutboundSubmitBtn) {
        queryOutboundSubmitBtn.addEventListener('click', handleQueryOutboundSubmit);
    }
    
    if (queryOutboundResetBtn) {
        queryOutboundResetBtn.addEventListener('click', handleQueryOutboundReset);
    }
    
    // 新增下发指令按钮事件
    if (sendInstructionsBtn) {
        sendInstructionsBtn.addEventListener('click', handleSendInstructions);
    }
    
    // 创建移库单表单提交
    if (addTransferForm) {
        addTransferForm.addEventListener('submit', handleAddTransferSubmit);
    }
    
    // 模块导航
    setupModuleNavigation();
    
    console.log('事件监听器绑定完成');
}

// 设置模块导航
function setupModuleNavigation() {
    const navLinks = document.querySelectorAll('.module-nav a');
    const sections = document.querySelectorAll('.module-section');
    
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 移除所有活动状态
            navLinks.forEach(l => l.classList.remove('active'));
            sections.forEach(s => s.classList.remove('active'));
            
            // 添加当前活动状态
            this.classList.add('active');
            const targetSection = document.querySelector(this.getAttribute('href'));
            if (targetSection) {
                targetSection.classList.add('active');
            }
        });
    });
}

// 显示登录界面
function showLoginSection() {
    console.log('显示登录界面');
    if (loginSection) loginSection.style.display = 'block';
    if (mainContent) mainContent.style.display = 'none';
}

// 显示主内容界面
function showMainContent() {
    console.log('显示主内容界面');
    if (loginSection) loginSection.style.display = 'none';
    if (mainContent) mainContent.style.display = 'block';
}

// 处理登录
function handleLogin(event) {
    event.preventDefault();
    
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    
    fetch(`${API_BASE_URL}/auth/login`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            authToken = data.data.token;
            localStorage.setItem('authToken', authToken);
            showMainContent();
            loadAllData();
        } else {
            alert('登录失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('登录失败:', error);
        alert('登录失败');
    });
}

// 处理登出
function handleLogout() {
    authToken = null;
    localStorage.removeItem('authToken');
    showLoginSection();
}

// 关闭所有模态框
function closeAllModals() {
    const modals = [viewInboundModal, viewOutboundModal, addTransferModal];
    modals.forEach(modal => {
        if (modal) modal.style.display = 'none';
    });
}

// 打开创建移库单模态框
function openAddTransferModal() {
    console.log('打开创建移库单模态框');
    if (addTransferModal) {
        if (addTransferForm) addTransferForm.reset();
        addTransferModal.style.display = 'block';
    }
}

// 处理创建移库单表单提交
function handleAddTransferSubmit(event) {
    event.preventDefault();
    
    const transferData = {
        goodsId: parseInt(document.getElementById('transferGoodsId').value),
        sourceLocation: document.getElementById('sourceLocation').value,
        targetLocation: document.getElementById('targetLocation').value,
        quantity: parseInt(document.getElementById('transferQuantity').value)
    };
    
    createTransfer(transferData);
}

// 处理库存搜索
function handleInventorySearch() {
    const keyword = inventorySearch ? inventorySearch.value : '';
    searchInventory(keyword);
}

// 处理开始盘点
function handleStartStocktaking() {
    alert('开始盘点功能待实现');
}

// 处理查询出库重置
function handleQueryOutboundReset() {
    // 重置所有查询条件
    if (queryMaterialName) queryMaterialName.value = '';
    if (queryMaterialCode) queryMaterialCode.value = '';
    if (queryLocation) queryLocation.value = '';
    if (queryAisle) queryAisle.value = '';
    if (queryRow) queryRow.value = '';
    if (queryColumn) queryColumn.value = '';
    if (queryLevel) queryLevel.value = '';
    if (queryEndEquipment) queryEndEquipment.value = '';
    if (queryAisleNumber) queryAisleNumber.value = '';
    
    // 清空表格
    if (outboundQueryTableBody) outboundQueryTableBody.innerHTML = '';
}

// 处理查询出库提交
function handleQueryOutboundSubmit() {
    console.log('执行查询出库');
    
    // 显示加载状态
    if (outboundQueryTableBody) {
        outboundQueryTableBody.innerHTML = '<tr><td colspan="9">加载中...</td></tr>';
    }
    
    // 获取查询条件
    const queryParams = {
        materialName: queryMaterialName ? queryMaterialName.value : '',
        materialCode: queryMaterialCode ? queryMaterialCode.value : '',
        location: queryLocation ? queryLocation.value : '',
        aisle: queryAisle ? queryAisle.value : '',
        row: queryRow ? queryRow.value : '',
        column: queryColumn ? queryColumn.value : '',
        level: queryLevel ? queryLevel.value : '',
        endEquipment: queryEndEquipment ? queryEndEquipment.value : '',
        aisleNumber: queryAisleNumber ? queryAisleNumber.value : ''
    };
    
    // 构建查询参数
    const params = new URLSearchParams();
    Object.keys(queryParams).forEach(key => {
        if (queryParams[key]) {
            params.append(key, queryParams[key]);
        }
    });
    
    // 从服务器获取数据
    fetch(`${API_BASE_URL}/outbound/query?${params.toString()}`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderOutboundQueryTable(data.data);
        } else {
            throw new Error(data.message || '获取数据失败');
        }
    })
    .catch(error => {
        console.error('查询出库数据失败:', error);
        if (outboundQueryTableBody) {
            outboundQueryTableBody.innerHTML = '<tr><td colspan="9">数据加载失败</td></tr>';
        }
        alert('查询出库数据失败: ' + error.message);
    });
}

// 加载所有数据
function loadAllData() {
    // 这里可以加载需要的初始数据
}

// 创建移库单
function createTransfer(transferData) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    fetch(`${API_BASE_URL}/transfers`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify(transferData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('移库单创建成功');
            closeAllModals();
            // 可以重新加载数据
        } else {
            alert('创建移库单失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('创建移库单失败:', error);
        alert('创建移库单失败');
    });
}

// 搜索库存
function searchInventory(keyword) {
    if (!authToken) return;
    
    fetch(`${API_BASE_URL}/goods`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                let filteredGoods = data.data;
                if (keyword) {
                    filteredGoods = data.data.filter(goods => 
                        goods.name.includes(keyword) || goods.sku.includes(keyword)
                    );
                }
                renderInventoryQueryTable(filteredGoods);
            }
        })
        .catch(error => {
            console.error('搜索库存数据失败:', error);
        });
}

// 渲染库存查询表格
function renderInventoryQueryTable(goodsList) {
    if (!inventoryQueryTableBody) return;
    
    inventoryQueryTableBody.innerHTML = '';
    
    goodsList.forEach(goods => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${goods.id}</td>
            <td>${goods.name}</td>
            <td>${goods.sku}</td>
            <td>${goods.quantity}</td>
            <td>${goods.location || '-'}</td>
            <td>${getStatusText(goods.status)}</td>
        `;
        inventoryQueryTableBody.appendChild(row);
    });
}

// 渲染查询出库表格
function renderOutboundQueryTable(data) {
    if (!outboundQueryTableBody) return;
    
    outboundQueryTableBody.innerHTML = '';
    
    data.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td><input type="checkbox" class="row-checkbox" data-id="${item.id}"></td>
            <td>${item.id}</td>
            <td>${item.location}</td>
            <td>${item.pallet || '-'}</td>
            <td>${item.materialCode}</td>
            <td>${item.materialName}</td>
            <td>${item.specification || '-'}</td>
            <td>${item.unit || '件'}</td>
            <td>${item.quantity}</td>
        `;
        outboundQueryTableBody.appendChild(row);
    });
    
    // 绑定全选复选框事件
    const selectAllCheckbox = document.getElementById('selectAllCheckbox');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('.row-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });
    }
    
    // 绑定行复选框事件
    const rowCheckboxes = document.querySelectorAll('.row-checkbox');
    rowCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            // 如果有任何一个未选中，则取消全选
            const allChecked = Array.from(rowCheckboxes).every(cb => cb.checked);
            if (selectAllCheckbox) {
                selectAllCheckbox.checked = allChecked;
            }
        });
    });
}

// 处理下发指令按钮点击事件
function handleSendInstructions() {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    // 获取所有选中的行
    const selectedCheckboxes = document.querySelectorAll('.row-checkbox:checked');
    if (selectedCheckboxes.length === 0) {
        alert('请至少选择一条记录');
        return;
    }
    
    // 获取选中的数据项ID
    const selectedIds = Array.from(selectedCheckboxes).map(cb => parseInt(cb.getAttribute('data-id')));
    
    // 从表格中获取选中的数据
    const selectedRows = [];
    selectedCheckboxes.forEach(cb => {
        const row = cb.closest('tr');
        const cells = row.querySelectorAll('td');
        selectedRows.push({
            id: parseInt(cb.getAttribute('data-id')),
            location: cells[2].textContent,
            pallet: cells[3].textContent,
            materialCode: cells[4].textContent,
            materialName: cells[5].textContent,
            specification: cells[6].textContent,
            unit: cells[7].textContent,
            quantity: parseInt(cells[8].textContent)
        });
    });
    
    // 获取仓库配置信息
    fetch('/api/config/warehouse')
        .then(response => response.json())
        .then(config => {
            if (config.success) {
                // 为每个选中的项创建出库指令
                createOutboundInstructions(selectedRows, config.data.aisles);
            } else {
                alert('获取仓库配置失败');
            }
        })
        .catch(error => {
            console.error('获取仓库配置失败:', error);
            alert('获取仓库配置失败');
        });
}

// 创建出库指令
function createOutboundInstructions(items, aisles) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    // 创建所有指令的Promise数组
    const createPromises = items.map(item => {
        // 解析货位号获取巷道信息
        const locationInfo = parseLocationInfo(item.location);
        if (!locationInfo) {
            return Promise.reject({ success: false, item, message: '货位号格式不正确' });
        }
        
        // 查找对应巷道的出库站台
        const aisle = aisles.find(a => a.code === locationInfo.aisle);
        const outboundStation = aisle && aisle.outboundStation ? aisle.outboundStation : { code: 'OUT01', name: '默认出库站台' };
        
        // 构造指令数据
        const instructionData = {
            taskId: '', // 让后端自动生成任务号
            taskType: '出库',
            palletId: item.pallet !== '-' ? item.pallet : '',
            startLocation: item.location,
            targetLocation: outboundStation.code,
            startDevice: `堆垛机${locationInfo.aisle}`, // 根据巷道确定起始设备
            endDevice: outboundStation.code,
            materialCode: item.materialCode,
            materialName: item.materialName,
            executeQuantity: item.quantity
        };
        
        // 发送创建指令请求
        return fetch('/api/instructions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`
            },
            body: JSON.stringify(instructionData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                return { success: true, item, message: '指令创建成功' };
            } else {
                return { success: false, item, message: '创建出库指令失败: ' + data.message };
            }
        })
        .catch(error => {
            console.error('创建出库指令失败:', error);
            return { success: false, item, message: '创建出库指令失败' };
        });
    });
    
    // 等待所有指令创建完成
    Promise.all(createPromises)
        .then(results => {
            // 统计成功和失败的数量
            const successCount = results.filter(r => r.success).length;
            const failCount = results.length - successCount;
            
            // 显示结果
            alert(`指令下发完成！成功: ${successCount}条，失败: ${failCount}条`);
            
            // 可以进一步处理结果，比如显示详细信息
            console.log('指令下发结果:', results);
        })
        .catch(error => {
            console.error('指令下发过程中出现错误:', error);
            alert('指令下发过程中出现错误');
        });
}

// 解析货位号获取位置信息
function parseLocationInfo(location) {
    // 假设货位号格式为 WH01-A-01-01-01
    const parts = location.split('-');
    
    if (parts.length !== 5) {
        return null; // 格式不正确
    }
    
    return {
        warehouse: parts[0],    // 仓库编号 (WH01)
        aisle: parts[1],        // 巷道号 (A)
        row: parts[2],          // 排 (01)
        column: parts[3],       // 列 (01)
        level: parts[4]         // 层 (01)
    };
}

// 获取单据状态文本
function getDocumentStatusText(status) {
    const statusMap = {
        'pending': '待处理',
        'received': '已接收',
        'picked': '已拣货',
        'shipped': '已发货',
        'completed': '已完成',
        'cancelled': '已取消'
    };
    return statusMap[status] || status;
}

// 获取货物状态文本
function getStatusText(status) {
    const statusMap = {
        'inStock': '在库',
        'outStock': '出库',
        'reserved': '预留'
    };
    return statusMap[status] || status;
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
}

// 查看入库单据详情
function viewInboundDocument(id) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    console.log('查看入库单据详情，ID:', id);
    
    fetch(`${API_BASE_URL}/inbound/${id}`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderInboundDetail(data.data);
            if (viewInboundModal) {
                viewInboundModal.style.display = 'block';
            }
        } else {
            alert('获取入库单据详情失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('获取入库单据详情失败:', error);
        alert('获取入库单据详情失败');
    });
}

// 渲染入库单据详情
function renderInboundDetail(document) {
    if (!inboundDetailContent) return;
    
    const detailHTML = `
        <div class="document-detail">
            <div class="detail-row">
                <span class="detail-label">单据ID:</span>
                <span class="detail-value">${document.id}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">货物ID:</span>
                <span class="detail-value">${document.goods_id}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">供应商:</span>
                <span class="detail-value">${document.supplier}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">数量:</span>
                <span class="detail-value">${document.quantity}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">预计到达日期:</span>
                <span class="detail-value">${formatDate(document.expected_arrival_date)}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">实际到达日期:</span>
                <span class="detail-value">${document.actual_arrival_date ? formatDate(document.actual_arrival_date) : '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">状态:</span>
                <span class="detail-value">${getDocumentStatusText(document.status)}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">操作员:</span>
                <span class="detail-value">${document.operator || '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">备注:</span>
                <span class="detail-value">${document.notes || '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">创建时间:</span>
                <span class="detail-value">${formatDate(document.created_at)}</span>
            </div>
            ${document.status === 'cancelled' ? `
            <div class="detail-row">
                <span class="detail-label">取消原因:</span>
                <span class="detail-value">${document.cancellation_reason || '-'}</span>
            </div>
            ` : ''}
        </div>
    `;
    
    inboundDetailContent.innerHTML = detailHTML;
}

// 查看出库单据详情
function viewOutboundDocument(id) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    console.log('查看出库单据详情，ID:', id);
    
    fetch(`${API_BASE_URL}/outbound/${id}`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderOutboundDetail(data.data);
            if (viewOutboundModal) {
                viewOutboundModal.style.display = 'block';
            }
        } else {
            alert('获取出库单据详情失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('获取出库单据详情失败:', error);
        alert('获取出库单据详情失败');
    });
}

// 渲染出库单据详情
function renderOutboundDetail(document) {
    if (!outboundDetailContent) return;
    
    const detailHTML = `
        <div class="document-detail">
            <div class="detail-row">
                <span class="detail-label">单据ID:</span>
                <span class="detail-value">${document.id}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">货物ID:</span>
                <span class="detail-value">${document.goods_id}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">客户:</span>
                <span class="detail-value">${document.customer}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">数量:</span>
                <span class="detail-value">${document.quantity}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">预计提货日期:</span>
                <span class="detail-value">${formatDate(document.expected_pickup_date)}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">实际提货日期:</span>
                <span class="detail-value">${document.actual_pickup_date ? formatDate(document.actual_pickup_date) : '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">状态:</span>
                <span class="detail-value">${getDocumentStatusText(document.status)}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">操作员:</span>
                <span class="detail-value">${document.operator || '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">备注:</span>
                <span class="detail-value">${document.notes || '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">创建时间:</span>
                <span class="detail-value">${formatDate(document.created_at)}</span>
            </div>
            ${document.status === 'cancelled' ? `
            <div class="detail-row">
                <span class="detail-label">取消原因:</span>
                <span class="detail-value">${document.cancellation_reason || '-'}</span>
            </div>
            ` : ''}
        </div>
    `;
    
    outboundDetailContent.innerHTML = detailHTML;
}